<template>
  <div class="app-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar" :class="{ collapsed: isCollapsed }">
      <div class="logo-container">
        <img
          src=""
          alt="心理健康"
          class="logo-image"
        />
        <span class="logo-text" v-show="!isCollapsed">心理健康管理系统</span>
      </div>

      <!-- 导航菜单 -->
      <el-menu
        :default-active="activeMenu"
        class="nav-menu"
        :collapse="isCollapsed"
        background-color="transparent"
        text-color="#666"
        active-text-color="#4086f4"
      >
        <!-- 所有角色都可见的菜单项 -->
        <el-menu-item index="home" @click="navigateTo('/home')">
          <el-icon><House /></el-icon>
          <template #title>首页</template>
        </el-menu-item>

        <el-menu-item index="profile" @click="navigateTo('/profile')">
          <el-icon><User /></el-icon>
          <template #title>个人中心</template>
        </el-menu-item>

        <!-- 基于角色动态显示菜单项 -->
        <admin-menu-items v-if="userRole === 'ADMIN'" @navigate="navigateTo" />
        <user-menu-items v-if="userRole === 'USER'" @navigate="navigateTo" />
        <psychologist-menu-items v-if="userRole === 'PSYCHOLOGIST'" @navigate="navigateTo" />
      </el-menu>

      <!-- 侧边栏底部折叠按钮 -->
      <div class="sidebar-collapse-btn" @click="toggleCollapse">
        <el-icon size="20">
          <Fold v-if="!isCollapsed" />
          <Expand v-else />
        </el-icon>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content" :class="{ expanded: isCollapsed }">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <h2>心理健康管理系统</h2>
        </div>
        <div class="header-right">
          <user-dropdown
            :username="username"
            :visible="dropdownVisible"
            @command="handleCommand"
            @visible-change="handleVisibleChange"
          />
        </div>
      </el-header>

      <!-- 内容区域 -->
      <div class="content">
        <el-card class="welcome-section" shadow="hover">
          <div class="welcome-header">
            <mindfulness-icon :size="32" stroke="#4086f4" class="welcome-icon" />
            <div class="welcome-text">
              <h1>欢迎使用心理健康管理系统</h1>
              <p>在这里，您可以进行心理测评、预约咨询、查看心理健康资讯等</p>
            </div>
          </div>
        </el-card>

        <!-- 快捷功能区 -->
        <div class="quick-access">
          <el-card shadow="hover" class="quick-card">
            <div class="card-icon">
              <mindfulness-icon :size="30" stroke="#4086f4" />
            </div>
            <h3>心理测评</h3>
            <p>进行心理健康测评，了解自己的心理状态</p>
            <el-button type="primary" class="card-btn" round @click="navigateTo('/assessment')">
              立即测评
            </el-button>
          </el-card>

          <el-card shadow="hover" class="quick-card">
            <div class="card-icon">
              <therapy-icon :size="30" stroke="#4086f4" />
            </div>
            <h3>预约咨询</h3>
            <p>预约专业心理咨询师，获取专业指导</p>
            <el-button type="primary" class="card-btn" round @click="navigateTo('/consultation')">
              立即预约
            </el-button>
          </el-card>

          <el-card shadow="hover" class="quick-card">
            <div class="card-icon">
              <wellness-icon :size="30" stroke="#4086f4" />
            </div>
            <h3>健康资讯</h3>
            <p>浏览心理健康相关知识，提高心理健康意识</p>
            <el-button type="primary" class="card-btn" round @click="navigateTo('/articles')">
              查看更多
            </el-button>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { House, User, Fold, Expand } from '@element-plus/icons-vue'
import { logout, getUserInfo } from '@/api/user'

// 导入组件
import AdminMenuItems from '@/components/menu/AdminMenuItems.vue'
import UserMenuItems from '@/components/menu/UserMenuItems.vue'
import PsychologistMenuItems from '@/components/menu/PsychologistMenuItems.vue'
import UserDropdown from '@/components/common/UserDropdown.vue'
import MindfulnessIcon from '@/components/common/MindfulnessIcon.vue'
import TherapyIcon from '@/components/common/TherapyIcon.vue'
import WellnessIcon from '@/components/common/WellnessIcon.vue'

const router = useRouter()
const username = ref('用户')
const userRole = ref('')
const isCollapsed = ref(false)
const activeMenu = ref('home')
const dropdownVisible = ref(false)

// 获取当前路由路径，设置激活菜单
const currentPath = computed(() => {
  return router.currentRoute.value.path.split('/')[1] || 'home'
})

// 初始化时设置激活菜单
onMounted(() => {
  activeMenu.value = currentPath.value

  // 检查是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }

  // 获取用户信息
  fetchUserInfo()
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      username.value = res.data.userName || '用户'
      userRole.value = res.data.role || 'USER'
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

// 折叠/展开侧边栏
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'logout') {
    handleLogout()
  }
}

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await logout()
        localStorage.removeItem('token')
        localStorage.removeItem('userRole')
        localStorage.removeItem('userName')
        localStorage.removeItem('accountId')
        ElMessage.success('退出成功')
        router.push('/login')
      } catch (error) {
        console.error('退出失败', error)
        ElMessage.error('退出失败，请重试')
      }
    })
    .catch(() => {})
}

// 处理下拉菜单可见性变化
const handleVisibleChange = (visible) => {
  dropdownVisible.value = visible
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', sans-serif;
}

.app-container {
  display: flex;
  min-height: 100vh;
  background: #f5f7fb;
  position: relative;
}

/* 侧边栏样式 */
.sidebar {
  width: 240px;
  background: #fff;
  border-right: 1px solid #eaedf2;
  display: flex;
  flex-direction: column;
  position: fixed;
  height: 100vh;
  z-index: 10;
  transition: width 0.3s;
}

.sidebar.collapsed {
  width: 64px;
}

.logo-container {
  padding: 20px;
  border-bottom: 1px solid #eaedf2;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  height: 60px;
}

.logo-image {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.logo-text {
  color: #4086f4;
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: opacity 0.3s;
}

.nav-menu {
  flex: 1;
  border-right: none;
  background-color: transparent;
}

.nav-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  margin: 5px 0;
}

.nav-menu :deep(.el-menu-item.is-active) {
  background: rgba(64, 134, 244, 0.1);
  border-right: 3px solid #4086f4;
}

.nav-menu :deep(.el-menu-item:hover) {
  background: rgba(64, 134, 244, 0.08);
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  margin-left: 240px;
  display: flex;
  flex-direction: column;
  transition: margin-left 0.3s;
}

.main-content.expanded {
  margin-left: 64px;
}

/* 顶部导航样式 */
.header {
  height: 60px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #eaedf2;
  padding: 0 20px;
}

.header-left h2 {
  color: #4086f4;
  font-size: 18px;
  font-weight: normal;
}

/* 内容区域样式 */
.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.welcome-section {
  margin-bottom: 20px;
}

.welcome-header {
  display: flex;
  align-items: center;
}

.welcome-icon {
  margin-right: 16px;
}

.welcome-text h1 {
  color: #333;
  font-size: 24px;
  margin-bottom: 10px;
  font-weight: normal;
}

.welcome-text p {
  color: #666;
  font-size: 14px;
}

/* 快捷功能区样式 */
.quick-access {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.quick-card {
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 30px 20px;
}

.quick-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(64, 134, 244, 0.15) !important;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #f0f5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.quick-card h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
  font-weight: normal;
}

.quick-card p {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.card-btn {
  padding: 8px 20px;
}

/* 添加新的侧边栏底部折叠按钮样式 */
.sidebar-collapse-btn {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  color: #666;
  cursor: pointer;
  border-top: 1px solid #eaedf2;
  margin-top: auto;
  transition: all 0.3s;
  padding-right: 20px;
}

.sidebar-collapse-btn:hover {
  color: #4086f4;
  background: rgba(64, 134, 244, 0.08);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 64px;
  }

  .sidebar.collapsed {
    width: 0;
    overflow: hidden;
  }

  .main-content {
    margin-left: 64px;
  }

  .main-content.expanded {
    margin-left: 0;
  }

  .quick-access {
    grid-template-columns: 1fr;
  }
}
</style>
